document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('register-form').addEventListener('submit', (event) => {
        event.preventDefault(); // 防止表单默认提交

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const email = document.getElementById('email').value;

        fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                'username': username,
                'password': password,
                'email': email
            })
        })

        .then(response => {
            return response.text().then(text => {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    throw new Error('服务器响应不是有效的 JSON: ' + text);
                }
            });
        })

        .then(data => {
            if (data.status === 'success') {
                alert("注册成功！");
                window.location.href = '/html/login.html';
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('发生错误，请重试！');
        });
    });
});
